import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import roc_curve, roc_auc_score, classification_report, confusion_matrix

# 读取数据
df = pd.read_excel('C:/Users/Administrator/Downloads/信用卡精准营销模型.xlsx')

# 检查数据
print(df.head())
print(df.info())
print(df.describe())

# 处理缺失值
df = df.dropna()

# 分离特征和目标变量
X = df.drop(columns='响应')
y = df['响应']

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123)
# 初始化AdaBoost分类器
clf = AdaBoostClassifier(random_state=123)

# 训练模型
clf.fit(X_train, y_train)

# 预测概率（用于ROC曲线）
y_pred_proba = clf.predict_proba(X_test)

# 预测类别
y_pred = clf.predict(X_test)
# 创建预测结果DataFrame
results = pd.DataFrame()
results['预测值'] = list(y_pred)
results['实际值'] = list(y_test)
print(results.head(10))

# 混淆矩阵
print("混淆矩阵:")
print(confusion_matrix(y_test, y_pred))

# 分类报告
print("\n分类报告:")
print(classification_report(y_test, y_pred))

# 计算ROC曲线
fpr, tpr, thres = roc_curve(y_test.values, y_pred_proba[:,1])
plt.figure(figsize=(8, 6))
plt.plot(fpr, tpr, label='AdaBoost')
plt.plot([0, 1], [0, 1], 'k--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve')
plt.legend()

# 保存图片
plt.savefig('ROC.png', dpi=300, bbox_inches='tight')

# 显示图片
plt.show()

# AUC得分
score = roc_auc_score(y_test, y_pred_proba[:,1])
print(f"\nAUC得分: {score:.4f}")